package com.runfast.common.web.filter;

import com.runfast.common.utils.LogUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: lijin
 * @date: 2018年06月26日
 */
@WebFilter
@Slf4j
public class RequestLoggingFilter extends OncePerRequestFilter {


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        long beginTime = System.currentTimeMillis();//1、开始时间

        boolean isFirstRequest = !isAsyncDispatch(request);
        HttpServletRequest requestToUse = request;
        ContentCachingResponseWrapper responseToUser = !(response instanceof ContentCachingResponseWrapper) ? new ContentCachingResponseWrapper(response) : (ContentCachingResponseWrapper) response;

        if (isFirstRequest && !(request instanceof ContentCachingRequestWrapper)) {
            requestToUse = new ContentCachingRequestWrapper(request);
        }

        try {
            filterChain.doFilter(requestToUse, responseToUser);
        } finally {
            if (!isAsyncStarted(requestToUse)) {

                if (isFirstRequest) LogUtils.loggingRequest(requestToUse);
                LogUtils.loggingResponse(responseToUser, beginTime);
                responseToUser.copyBodyToResponse();
            }
        }
    }


}
